package cn.kgc.javaweb.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: mosin
 * @version: v1.0  2022/3/17
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //设置请求的编码格式  设置编码格式 一定要在获取参数之前  否则无效  post
        req.setCharacterEncoding("utf-8");
        //获取前端页面传递的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String rem = req.getParameter("rem");

        System.out.println("username = " + username);

        //根据用户名和密码查询数据库  admin  888888

        if("admin".equals(username)&&"888888".equals(password)){ // 登录成功 跳转主页

                if("true".equals(rem)){  // 记住我   将用户名和密码响应给前端保存  cookie

                    Cookie ck1 = new Cookie("username", username);
                    Cookie ck2 = new Cookie("password", password);
                    Cookie ck3 = new Cookie("rem", rem);

                    //将ck1 和ck2 响应到前端
                    resp.addCookie(ck1);
                    resp.addCookie(ck2);
                    resp.addCookie(ck3);

                }else{

                    Cookie ck1 = new Cookie("username", username);
                    Cookie ck2 = new Cookie("password", password);
                    Cookie ck3 = new Cookie("rem", rem);

                    //设置cookie的存活时间
                    ck1.setMaxAge(0);  // 立即删除
                    ck2.setMaxAge(0);
                    ck3.setMaxAge(0);

                    //将ck1 和ck2 响应到前端
                    resp.addCookie(ck1);
                    resp.addCookie(ck2);
                    resp.addCookie(ck3);
                }

                //登录成功 重定向到主页
                resp.sendRedirect("index.jsp");

        }else{ // 登录失败     停在登录页
             req.setAttribute("info","用户名或者密码错误");
             req.getRequestDispatcher("login.jsp").forward(req,resp);
        }

    }
}
